import React, { useState, useEffect } from 'react';
import { Table, Input, Select, Button, Space, Tooltip, Tag, Empty, message } from 'antd';
import { SearchOutlined, ClearOutlined, EyeOutlined, LinkOutlined } from '@ant-design/icons';
import { DubboProviderDTO, getDubboProviders, GetProvidersParams } from '../../../../services/dubboAnalysis';
import { buildFileLink } from '../../../../utils/gitUrlUtils';
import type { ColumnsType, TablePaginationConfig } from 'antd/es/table';
import type { SorterResult, FilterValue } from 'antd/es/table/interface';

const { Option } = Select;

interface DubboProviderTableProps {
    unitId: string;
    unitInfo?: any; // 添加 unitInfo 以获取 Git 仓库信息
    onViewReferences: (provider: DubboProviderDTO) => void;
}

const DubboProviderTable: React.FC<DubboProviderTableProps> = ({ unitId, unitInfo, onViewReferences }) => {
    const [loading, setLoading] = useState<boolean>(false);
    const [providers, setProviders] = useState<DubboProviderDTO[]>([]);
    const [filteredProviders, setFilteredProviders] = useState<DubboProviderDTO[]>([]);
    
    // 筛选条件
    const [searchKeyword, setSearchKeyword] = useState<string>('');
    const [selectedGroup, setSelectedGroup] = useState<string | undefined>(undefined);
    const [selectedVersion, setSelectedVersion] = useState<string | undefined>(undefined);
    
    // 排序状态
    const [sortField, setSortField] = useState<string | undefined>(undefined);
    const [sortOrder, setSortOrder] = useState<'ascend' | 'descend' | undefined>(undefined);

    // 获取唯一的服务分组列表
    const getUniqueGroups = (): string[] => {
        const groups = providers
            .map(p => p.serviceGroup)
            .filter((g): g is string => !!g);
        return Array.from(new Set(groups)).sort();
    };

    // 获取唯一的版本号列表
    const getUniqueVersions = (): string[] => {
        const versions = providers
            .map(p => p.version)
            .filter((v): v is string => !!v);
        return Array.from(new Set(versions)).sort();
    };

    // 加载 Provider 数据
    const loadProviders = async () => {
        setLoading(true);
        try {
            const data = await getDubboProviders(unitId);
            setProviders(data);
            applyFilters(data, searchKeyword, selectedGroup, selectedVersion);
        } catch (error: any) {
            message.error(error.message || '加载 Provider 列表失败');
            setProviders([]);
            setFilteredProviders([]);
        } finally {
            setLoading(false);
        }
    };

    // 应用筛选条件
    const applyFilters = (
        data: DubboProviderDTO[],
        keyword: string,
        group: string | undefined,
        version: string | undefined
    ) => {
        let filtered = [...data];

        // 按接口名称搜索（模糊匹配）
        if (keyword.trim()) {
            const lowerKeyword = keyword.toLowerCase();
            filtered = filtered.filter(p =>
                p.interfaceFqn.toLowerCase().includes(lowerKeyword) ||
                p.interfaceSimpleName.toLowerCase().includes(lowerKeyword)
            );
        }

        // 按服务分组筛选
        if (group) {
            filtered = filtered.filter(p => p.serviceGroup === group);
        }

        // 按版本号筛选
        if (version) {
            filtered = filtered.filter(p => p.version === version);
        }

        setFilteredProviders(filtered);
    };

    // 处理搜索
    const handleSearch = (value: string) => {
        setSearchKeyword(value);
        applyFilters(providers, value, selectedGroup, selectedVersion);
    };

    // 处理服务分组筛选
    const handleGroupChange = (value: string | undefined) => {
        setSelectedGroup(value);
        applyFilters(providers, searchKeyword, value, selectedVersion);
    };

    // 处理版本号筛选
    const handleVersionChange = (value: string | undefined) => {
        setSelectedVersion(value);
        applyFilters(providers, searchKeyword, selectedGroup, value);
    };

    // 重置所有筛选条件
    const handleReset = () => {
        setSearchKeyword('');
        setSelectedGroup(undefined);
        setSelectedVersion(undefined);
        setSortField(undefined);
        setSortOrder(undefined);
        setFilteredProviders(providers);
    };

    // 处理表格变化（排序）
    const handleTableChange = (
        pagination: TablePaginationConfig,
        filters: Record<string, FilterValue | null>,
        sorter: SorterResult<DubboProviderDTO> | SorterResult<DubboProviderDTO>[]
    ) => {
        if (!Array.isArray(sorter)) {
            setSortField(sorter.field as string);
            setSortOrder(sorter.order === null ? undefined : sorter.order);
        }
    };

    // 初始加载
    useEffect(() => {
        loadProviders();
    }, [unitId]);

    // 构建 GitLab 文件链接
    const buildGitLabLink = (filePath: string, lineNumber?: number): string => {
        if (!unitInfo?.gitRepoUrl || !filePath) return '';
        const branch = unitInfo.currentBranch || unitInfo.defaultBranch || 'master';
        return buildFileLink(unitInfo.gitRepoUrl, filePath, branch, lineNumber, lineNumber);
    };

    // 从后往前截断文本（保留后面部分）
    const truncateFromStart = (text: string, maxLength: number = 20): string => {
        if (!text || text.length <= maxLength) return text;
        return '...' + text.slice(-(maxLength - 3));
    };

    // 表格列定义
    const columns: ColumnsType<DubboProviderDTO> = [
        {
            title: '接口名称',
            dataIndex: 'interfaceSimpleName',
            key: 'interfaceSimpleName',
            width: 200,
            fixed: 'left',
            sorter: (a, b) => a.interfaceFqn.localeCompare(b.interfaceFqn),
            sortOrder: sortField === 'interfaceSimpleName' ? sortOrder : undefined,
            render: (text: string, record: DubboProviderDTO) => (
                <Tooltip title={record.interfaceFqn} placement="topLeft">
                    <span style={{ 
                        fontWeight: 500, 
                        color: '#1890ff',
                        cursor: 'pointer'
                    }}>
                        {text}
                    </span>
                </Tooltip>
            ),
        },
        {
            title: '版本号',
            dataIndex: 'version',
            key: 'version',
            width: 100,
            render: (text: string) => text || <span style={{ color: '#999' }}>-</span>,
        },
        {
            title: '实现Bean',
            dataIndex: 'implBean',
            key: 'implBean',
            width: 200,
            render: (text: string) => {
                if (!text) return <span style={{ color: '#999' }}>-</span>;
                return (
                    <Tooltip title={text} placement="topLeft">
                        <span style={{ 
                            whiteSpace: 'nowrap',
                            overflow: 'hidden',
                            textOverflow: 'ellipsis',
                            display: 'block',
                            direction: 'rtl',
                            textAlign: 'left'
                        }}>
                            {text}
                        </span>
                    </Tooltip>
                );
            },
        },
        {
            title: '模块名称',
            dataIndex: 'moduleName',
            key: 'moduleName',
            width: 150,
            render: (text: string) => text || <span style={{ color: '#999' }}>-</span>,
        },
        {
            title: '配置文件位置',
            key: 'fileLocation',
            width: 280,
            ellipsis: {
                showTitle: false,
            },
            render: (_, record: DubboProviderDTO) => {
                const gitLabLink = buildGitLabLink(record.filePath, record.lineNumber);
                const displayText = record.lineNumber 
                    ? `${record.filePath}:${record.lineNumber}`
                    : record.filePath;
                
                return gitLabLink ? (
                    <Tooltip title={`点击跳转到 GitLab: ${displayText}`} placement="topLeft">
                        <a 
                            href={gitLabLink}
                            target="_blank"
                            rel="noopener noreferrer"
                            style={{ 
                                color: '#1890ff',
                                display: 'flex',
                                alignItems: 'center',
                                gap: '4px'
                            }}
                        >
                            <LinkOutlined style={{ fontSize: '12px' }} />
                            <span style={{ 
                                flex: 1,
                                overflow: 'hidden',
                                textOverflow: 'ellipsis',
                                whiteSpace: 'nowrap'
                            }}>
                                {displayText}
                            </span>
                        </a>
                    </Tooltip>
                ) : (
                    <Tooltip title={displayText} placement="topLeft">
                        <span style={{ color: '#666', fontSize: '12px' }}>{displayText}</span>
                    </Tooltip>
                );
            },
        },
        {
            title: '被引用',
            key: 'references',
            width: 100,
            align: 'center',
            fixed: 'right',
            sorter: (a, b) => a.referencedCount - b.referencedCount,
            sortOrder: sortField === 'referencedCount' ? sortOrder : undefined,
            render: (_, record: DubboProviderDTO) => {
                const count = record.referencedCount;
                return count > 0 ? (
                    <Tooltip title="点击查看引用详情">
                        <Tag 
                            color="green" 
                            style={{ 
                                fontWeight: 500,
                                cursor: 'pointer',
                                fontSize: '13px',
                                padding: '2px 8px'
                            }}
                            onClick={() => onViewReferences(record)}
                        >
                            {count} 次
                        </Tag>
                    </Tooltip>
                ) : (
                    <Tag color="default" style={{ fontWeight: 500 }}>
                        0 次
                    </Tag>
                );
            },
        },
    ];

    return (
        <div style={{ marginBottom: '24px' }}>
            {/* 标题 */}
            <div style={{
                fontSize: '18px',
                fontWeight: '600',
                color: '#333',
                marginBottom: '16px',
                display: 'flex',
                alignItems: 'center'
            }}>
                <span style={{ 
                    display: 'inline-block',
                    width: '4px',
                    height: '18px',
                    background: '#52c41a',
                    marginRight: '8px',
                    borderRadius: '2px'
                }} />
                提供的服务列表
            </div>

            {/* 筛选栏 */}
            <div style={{
                background: '#fff',
                padding: '16px',
                borderRadius: '8px',
                marginBottom: '16px',
                boxShadow: '0 2px 8px rgba(0,0,0,0.06)'
            }}>
                <Space size="middle" wrap>
                    {/* 搜索框 */}
                    <Input
                        placeholder="按接口名称搜索..."
                        prefix={<SearchOutlined style={{ color: '#bfbfbf' }} />}
                        value={searchKeyword}
                        onChange={(e) => handleSearch(e.target.value)}
                        onPressEnter={() => handleSearch(searchKeyword)}
                        allowClear
                        style={{ width: 280 }}
                    />

                    {/* 服务分组筛选 */}
                    <Select
                        placeholder="选择服务分组"
                        value={selectedGroup}
                        onChange={handleGroupChange}
                        allowClear
                        style={{ width: 180 }}
                    >
                        {getUniqueGroups().map(group => (
                            <Option key={group} value={group}>{group}</Option>
                        ))}
                    </Select>

                    {/* 版本号筛选 */}
                    <Select
                        placeholder="选择版本号"
                        value={selectedVersion}
                        onChange={handleVersionChange}
                        allowClear
                        style={{ width: 150 }}
                    >
                        {getUniqueVersions().map(version => (
                            <Option key={version} value={version}>{version}</Option>
                        ))}
                    </Select>

                    {/* 重置按钮 */}
                    <Button
                        icon={<ClearOutlined />}
                        onClick={handleReset}
                    >
                        重置
                    </Button>
                </Space>

                {/* 筛选结果提示 */}
                {(searchKeyword || selectedGroup || selectedVersion) && (
                    <div style={{ 
                        marginTop: '12px', 
                        fontSize: '13px', 
                        color: '#666' 
                    }}>
                        已筛选 <span style={{ color: '#1890ff', fontWeight: 500 }}>{filteredProviders.length}</span> 条结果
                        {searchKeyword && ` · 关键词: "${searchKeyword}"`}
                        {selectedGroup && ` · 分组: ${selectedGroup}`}
                        {selectedVersion && ` · 版本: ${selectedVersion}`}
                    </div>
                )}
            </div>

            {/* 表格 */}
            <Table
                columns={columns}
                dataSource={filteredProviders}
                rowKey="configId"
                loading={loading}
                onChange={handleTableChange}
                pagination={{
                    pageSize: 20,
                    showSizeChanger: true,
                    showQuickJumper: true,
                    showTotal: (total) => `共 ${total} 条`,
                    pageSizeOptions: ['10', '20', '50', '100'],
                }}
                scroll={{ x: 1200 }}
                locale={{
                    emptyText: (
                        <Empty
                            description={
                                <span style={{ color: '#999' }}>
                                    {searchKeyword || selectedGroup || selectedVersion
                                        ? '没有找到匹配的服务'
                                        : '暂无提供的服务'}
                                </span>
                            }
                        />
                    ),
                }}
                style={{
                    background: '#fff',
                    borderRadius: '8px',
                    boxShadow: '0 2px 8px rgba(0,0,0,0.06)'
                }}
            />
        </div>
    );
};

export default DubboProviderTable;
